package com.googlecode.jtoy.patterns.command;

/**
 * 实现多线程控制的一项古老技术
 * 
 * @author shangxj
 * @date Jun 20, 2011 10:30:16 PM
 */
public class DelayedTyper implements Command {

	private long delay;
	private char c;
	private static ActiveObjectEngine engine = new ActiveObjectEngine();
	private static boolean stop = false;

	public DelayedTyper(long delay, char c) {

		this.delay = delay;
		this.c = c;
	}

	@Override
	public void execute() throws Exception {

		System.out.print(c);
		if (!stop) {
			delayAndRepeat();
		}
	}

	private void delayAndRepeat() throws CloneNotSupportedException {

		engine.addCommand(new SleepCommand(delay, engine, this));
	}

	public static void main(String args[]) throws Exception {

		engine.addCommand(new DelayedTyper(100, '1'));
		engine.addCommand(new DelayedTyper(300, '3'));
		engine.addCommand(new DelayedTyper(500, '5'));
		engine.addCommand(new DelayedTyper(700, '7'));

		Command wakeupCommand = new Command() {

			@Override
			public void execute() {

				stop = true;
			}
		};

		engine.addCommand(new SleepCommand(20000, engine, wakeupCommand));
		engine.run();
	}

}
